﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WpfWordsLearner.ViewModels;
using System.Threading.Tasks;

namespace WpfWordsLearner.Views
{
	/// <summary>
	/// Interaktionslogik für Window1.xaml
	/// </summary>
	public partial class Window1 : Window
	{
		public static RoutedCommand TranslateCommand = new RoutedCommand();
		public static RoutedCommand LearnCommand = new RoutedCommand();

		bool m_isTranslatioEnabled = false;

		public Window1()
		{
			InitializeComponent();
			this.Loaded += new RoutedEventHandler(Window1_Loaded);

			this.CommandBindings.Add(new CommandBinding(TranslateCommand, (s, e) =>
				{
					Views.TranslateWindow window = new TranslateWindow();
					window.Owner = this;
					window.ShowInTaskbar = false;
					window.ShowActivated = true;
					window.DataContext = new ViewModels.TranslateViewModel();
					window.ShowDialog();
				},
				(s, e) => e.CanExecute = (m_isTranslatioEnabled)));

			this.InputBindings.Add(new KeyBinding(TranslateCommand, new KeyGesture(Key.T, ModifierKeys.Control)));

			this.CommandBindings.Add(new CommandBinding(LearnCommand, (s, e) =>
			{
				Views.LearnView window = new LearnView();
				window.Owner = this;
				window.ShowInTaskbar = false;
				window.ShowActivated = true;
				var vm = new ViewModels.LearnViewModel();
				vm.Interval = 4000;
				vm.SetDispatcher(window.Dispatcher);
				window.DataContext = vm;

				window.ShowDialog();
			},
				(s, e) => e.CanExecute = true));

			this.InputBindings.Add(new KeyBinding(LearnCommand, new KeyGesture(Key.L, ModifierKeys.Control)));
		}

		void Window1_Loaded(object sender, RoutedEventArgs e)
		{
			miTranslate.Command = TranslateCommand;
			miLearning.Command = LearnCommand;

			Task task = new Task(new Action(() =>
				{
					using (ServiceReferenceTranslater.TranslateServiceClient client = new ServiceReferenceTranslater.TranslateServiceClient())
					{
						client.Open();
						if (client.State == System.ServiceModel.CommunicationState.Opened)
							client.Close();
					}
					m_isTranslatioEnabled = true;
				}));

			task.ContinueWith(prevTask =>
				{
					m_isTranslatioEnabled = false;
					App.Log.Error("Error occurred while trying to conect to translation service", prevTask.Exception);
					prevTask.Dispose();
				}, TaskContinuationOptions.NotOnRanToCompletion);

			task.Start();
		}
	}
}
